<template>
  <el-select
    :multiple="multiple"
    :collapse-tags="collapseTags"
    :clearable="clearable"
    :size="size"
    :placeholder="placeholder"
    :loading="loading"
    :disabled="disabled"
    class="fg-select"
    v-model="selected"
    >
    <el-option
      v-for="item in optionsData"
      :key="item.id"
      :label="item.label"
      :value="item.value"></el-option>
  </el-select>
</template>
<script>
import { getDict } from './dg-api.js';

export default {
  name: 'dg-select',
  // 通过props来接受从父组件传递过来的值
  // {placeholder; multiple: 多选; clearable: 清空; size: 尺寸; disabled: 禁用; dictType: 字典类型; defaultValue: 默认值}
  props: ['placeholder', 'multiple', 'collapseTags', 'clearable', 'size', 'disabled', 'dictType', 'defaultValue'],
  model: {
    event: 'change'
  },
  data () {
    return {
      selected: this.defaultValue || this.defaultValue === 0 ? this.defaultValue.toString() : this.defaultValue,
      loading: false,
      optionsData: []
    };
  },
  mounted () {
    this.remoteMethod();
  },
  methods: {
    /*
      * @date 2019-06-19
      * @author wolfMan
      * @description {获取数据源}
      * @param {} 无
    */
    remoteMethod () {
      let _params = {
        'type': this.dictType
      };
      getDict(_params).then(_res => {
        let _data = _res.data;
        if (_data.length > 0) {
          this.optionsData = _data;
        } else {
          this.$messageError(_data.message);
        }
      });
    }
  },
  watch: {
    defaultValue: function (val) {
      let _val = val;
      if (_val || _val === 0) {
        _val = val.toString();
      }
      this.selected = _val;
    },
    selected: function (val) {
      let _val = val;
      if (this.multiple === undefined || typeof (_val) !== 'object') {
        if (_val || _val === 0) {
          _val = val.toString();
        }
      }
      this.$emit('change', _val);
    }
  }
};
</script>
